import axios from "axios";
import {BASE_URL,flask_url} from "./config";

const instance = axios.create({
  baseURL: BASE_URL,
  timeout: 10000,
  headers: {
    "Content-Type": "application/json"
  }
});

// 请求拦截器：自动加 token（从 user 里面取）
instance.interceptors.request.use(config => {
  // 如果是登录接口，不加 token
  if (config.url.includes("/auth/login")) {
    return config;
  }

  const token = localStorage.getItem("token");
  if (token) {
    try {
        // 检查 token 是否已经包含 Bearer 前缀
        if (token.startsWith("Bearer ")) {
          config.headers.Authorization = token;
        } else {
          config.headers.Authorization = `Bearer ${token}`;
        }
    } catch (e) {
      console.error("解析 userInfo 出错", e);
    }
  }

  return config;
}, error => Promise.reject(error));



// 响应拦截器：比如 401 未登录，清除本地
instance.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("user");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);
const plainAxios = axios.create({
  baseURL: BASE_URL,
  timeout: 5000,
  headers: {
    "Content-Type": "application/json"
  },
  responseType: "blob", // 这里必须是 blob，才能处理文件流
});

plainAxios.interceptors.request.use(config => {
  if (config.url.includes("/auth/login")) {
    return config;
  }

  const token = localStorage.getItem("token");
  if (token) {
    // 检查 token 是否已经包含 Bearer 前缀
    if (token.startsWith("Bearer ")) {
      config.headers.Authorization = token;
    } else {
      config.headers.Authorization = `Bearer ${token}`;
    }
  }

  return config;
}, error => Promise.reject(error));

// 响应拦截器不拆 data，保持原始 response，方便获取 headers
plainAxios.interceptors.response.use(
  response => response,
  error => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("user");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);
const instanceFlask = axios.create({
  baseURL: "http://192.168.10.58",
  timeout: 5000,
  headers: {
    "Content-Type": "application/json"
  }
});

// 请求拦截器：自动加 token（从 user 里面取）
instanceFlask.interceptors.request.use(config => {
  // 如果是登录接口，不加 token
  if (config.url.includes("/auth/login")) {
    return config;
  }

  const token = localStorage.getItem("token");
  if (token) {
    try {
        config.headers.Authorization = `Bearer ${token}`;
    } catch (e) {
      console.error("解析 userInfo 出错", e);
    }
  }

  return config;
}, error => Promise.reject(error));



// 响应拦截器：比如 401 未登录，清除本地
instanceFlask.interceptors.response.use(
  response => response.data,
  error => {
    if (error.response && error.response.status === 401) {
      localStorage.removeItem("user");
      window.location.href = "/login";
    }
    return Promise.reject(error);
  }
);
export { instance, plainAxios,instanceFlask };
